import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;

public class addHouse extends HttpServlet
{
	public static dbapi conn;
	// Add House to database
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException
	{
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		conn = new dbapi();
		// Create connection to Oracle
		conn.connect();
		out.println(htmlHeader.header);
		// Error if servlet cannot connect to Oracle
		if(!conn.connected)
		{
			out.println("CANT CONNECT! <br>");
			out.println(conn.msg + "<br>");
			return;
		}
		// Get variables
		String address = request.getParameter("ADDRESS");
		String city = request.getParameter("CITY");
		String state = request.getParameter("STATE");
		String zipcode = request.getParameter("ZIPCODE");
		String floorSpace = request.getParameter("SQFT");
		String numFloors = request.getParameter("FLOORS");
		String numBedrooms = request.getParameter("BEDROOMS");
		String numBathrooms = request.getParameter("BATHROOMS");
		String landSize	= request.getParameter("LANDSIZE");
		String year = request.getParameter("YEAR");
		String homeClass = request.getParameter("HOMECLASS");

		// Error handling for blank form
		if(floorSpace == "" || numFloors == "" || numBedrooms == ""
		|| numBathrooms == "" || landSize == "" || year == "" 
		|| address == "" || city == "" || state == "" || zipcode == "" 
		|| homeClass == "")
		{
			out.println("ERROR: not all fields were filled in");
			return;
		}

		// dbapi call to add house to database
		boolean worked = conn.newHome(
				address,
				city,
				state,
				Integer.parseInt(zipcode),
				Integer.parseInt(floorSpace),
				Integer.parseInt(numFloors),
				Integer.parseInt(numBedrooms),
				Integer.parseInt(numBathrooms),
				Integer.parseInt(landSize),
				Integer.parseInt(year),
				homeClass);

		// Get last homeid to refresh to (bad practice but for this project will be ok)
		int homeID = conn.getLastHomeID();
		// Error if adding the home did not work
		// or refresh to house list on success
		if (!worked)
		{
			out.println(conn.msg);
		}else{
			out.println("House Added Successfully...");
			out.println("<header><meta http-equiv=\"refresh\" content=\"2;houseDetails?id="+homeID+"\"></header>");
		}
		return;
	}
}
